package com.duoec.doc.service.impl.mock.base;

import com.alibaba.fastjson.JSONObject;
import com.duoec.doc.entity.MockConfigItem;
import com.duoec.doc.helper.CharHelper;
import com.duoec.doc.helper.MockHelper;
import com.duoec.doc.service.IBaseTypeMocker;
import com.duoec.doc.service.IMocker;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Random;

/**
 * @author xuwenzhen
 * @date 2020/2/1
 */
@Service
public class StringBaseTypeMocker implements IMocker, IBaseTypeMocker {
    /**
     * mock配置输出的响应
     *
     * @param item 配置
     * @return
     */
    @Override
    public String mock(MockConfigItem item) {
        if (!MockHelper.available(item)) {
            return null;
        }
        return JSONObject.toJSONString(getMockValue(item));
    }

    private Object getMockValue(MockConfigItem item) {
        Integer mockType = item.getMockType();
        switch (mockType) {
            case 2:
            case 3:
                //备选中随机
                List<String> list = item.getMockValueRandomList();
                if (CollectionUtils.isEmpty(list)) {
                    return null;
                }
                return list.get(new Random().nextInt(list.size()));
            case 4:
                //随机N个字符串
                Integer start = item.getMockValueStart();
                Integer end = item.getMockValueEnd();
                if (start == null) {
                    start = 0;
                }
                if (end == null) {
                    end = 100;
                }
                int count = start + new Random().nextInt(end - start);
                return CharHelper.randomChinese(count);
            default:
                return item.getValue();
        }
    }

    /**
     * 可处理的基础类型：0=number 1=string 2=boolean 3=byte 4=date 5=enum 6=char
     *
     * @return 类型
     */
    @Override
    public Integer getMockType() {
        return 1;
    }
}
